<?php
namespace app\api\controller;

use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use think\facade\Cache;

class AcceptCd
{
    private $redis;

    public function __construct()
    {
        $this->redis = Cache::store('redis')->handler();
    }

    public function index()
    {
        $params = Request::param();
        //记录日志
        $time   = getUtcTime(false);
        Log::write("accept_info({$time})-----------------------start\n");
        Log::write($params);
        Log::write("\n");

        if(!is_array($params)){
            $params = json_decode($params , true);
        }
        if(!isset($params['event'])){
            Log::write("({$time})Error: The Token parameter does not exist.----------------------------------------end\n");
            exit;
        }
        //公共参数
        $request    = json_encode($params);
        $ctime      = getUtcTime();

        //api详情---这里只处理消费日志,即 api_event="card-transaction-events"
        $api_event          = $params['event'];
        if($api_event != "card-transaction-events"){
            Log::write("({$time})Error: event !='card-transaction-events'------------------------------------------end\n");
            exit;
        }
        //customer
        $api_customer_array= $params['customer'] ?? '';
        $api_customer_id   = $api_customer_array['id'] ?? '';
        $api_customer_code = $api_customer_array['accountNumber'] ?? '';

        //elements
        $api_elements_array = $params['elements'][0];
        $api_element_json   = json_encode($api_elements_array);

        //elements-card
        $tran_card_array= $api_elements_array['card'] ?? '';
        $tran_card_token= $tran_card_array['token'] ?? '';
        $employeeNumber = $tran_card_array['employeeNumber'] ?? '';

        $api_type       = $api_elements_array['type'];
        $approvalCode   = $api_elements_array['approvalCode'];
        $decline_error  = $api_elements_array['correctiveAction'] ?? '';
        $auth_amount    = $api_elements_array['preAuthAmount'] ?? '';
        $post_amount    = $api_elements_array['postedAmount'] ?? '';
        $authorizationTime= $api_elements_array['authorizationTime'] ?? '';
        if(!empty($authorizationTime)){
            $authorizationTime = substr($authorizationTime , 0 , 19);
        }
        $transactionTime= $api_elements_array['transactionTime'] ?? '';
        if(!empty($transactionTime)){
            $transactionTime = substr($transactionTime , 0 , 19);
        }
        $reversalFlag   = $api_elements_array['reversalFlag'] ?? '';
        $idMatchNumber  = $api_elements_array['idMatchNumber'] ?? '';
        //elements-pos
        $tran_pos_array = $api_elements_array['pos'] ?? '';
        $shopping       = $tran_pos_array['acceptLocation'] ?? '';
        $mcc            = $api_elements_array['merchant']['mcc'] ?? '';
        $country        = !empty($shopping) ? substr($shopping , -2) : '';
        $currencyCode   = 'USD';


        //根据card_token查询是否是本系统的卡
        $card_list      = Db::name('cards')
            ->where(['card_token' => $tran_card_token])
            ->find();
        if(empty($card_list)){
            Log::write("Error: Card not find(CD) \n");
            http_response_code(200);
            echo "success";
            exit;
        }

        $card_num           = $card_list['card_num'];
        $user_id            = $card_list['user_id'];
        $bank_type          = $card_list['bank_type'];
        $card_status        = $card_list['status'];

        $result = Db::name('api_accept_com')->insertGetId([
            'user_id'       =>  $user_id,
            'card_num'      =>  $card_num,
            'tran_type'     =>  $api_type,
            'flag'          =>  $reversalFlag,
            'idMatchNumber' =>  $idMatchNumber,
            'auth_amount'   =>  $auth_amount,
            'post_amount'   =>  $post_amount,
            'auth_time'     =>  $authorizationTime,
            'post_time'     =>  $transactionTime,
            'app_code'      =>  $approvalCode,
            'shopping'      =>  $shopping,
            'json_data'     =>  $api_element_json,
            'is_new'        =>  1   //2025-02-28 为新一轮更新
        ]);

        //关键字豁免用户
        $keyword_exempt_users = getSetting('keyword_exempt_users');
        $keyword_exempt_users_array = explode(',' , $keyword_exempt_users);
        $key_users = [];
        foreach ($keyword_exempt_users_array as $k_users=>$v_users) {
            $key_users[] = Db::name('user')->where(['username' => $v_users])->value('id');
        }
        //不存在豁免的用户进行关键字排查
        if(!in_array($user_id,$key_users)){
            //记录违规关键字消费记录
            $getDelKey = getSetting('tran_key_name');
            $key_array = explode(',' , $getDelKey);
            foreach ($key_array as $k_ka=>$v_ka) {
                //判断字符串中存在子字符串
                if (strpos(strtolower($shopping), strtolower($v_ka)) !== false) {
                    Db::name('user_ice_log')->save([
                        'user_id'   =>  $user_id,
                        'card_num'  =>  $card_num,
                        'type'      =>  0,    //0关键字，1超额
                        'key_name'  =>  $v_ka,
                        'amount_auth'   => $auth_amount,
                        'amount_post'   => $post_amount,
                        'bank_type'     => $bank_type,
                        'card_status'   => $card_status,
                        'ctime'         => $ctime,
                        'mcc'           => $mcc
                    ]);
                }
            }
        }

        if($api_type == 'POST'){
            //记录实际扣款($) >预扣款($)*1.05 , 1.05可在配置修改
            $getAmountPost = getSetting('amount_post_limit');
            if(!empty($post_amount)){
                if($post_amount  - ($auth_amount * $getAmountPost) > 0){
                    Db::name('user_ice_log')->save([
                        'user_id'   =>  $user_id,
                        'card_num'  =>  $card_num,
                        'type'      =>  1,    //0关键字，1超额
                        'amount_auth'   => $auth_amount,
                        'amount_post'   => $post_amount,
                        'bank_type'     => $bank_type,
                        'card_status'   => $card_status,
                        'ctime'         => $ctime,
                        'mcc'           => $mcc
                    ]);
                }
            }
        }
        Log::write("accept_info({$time})-----------------------end\n");

        http_response_code(200);
        echo "success";
    }
}
